from django.db import models
from apps.system.models import Upload, Option

from utils.exceptions import CustomError


class ProductParameter(models.Model):
    parameter = models.CharField(verbose_name='产品参数', max_length=150)
    value = models.CharField(verbose_name='参数值', max_length=150)

    class Meta:
        db_table = 'product_parameter'
        verbose_name = '产品参数'

    @staticmethod
    def get_instance_by_id(id):
        try:
            id = int(id)
        except:
            raise CustomError('无效的参数id')

        instance = ProductParameter.objects.filter(pk=id).first()
        if not instance:
            raise CustomError('未找到对应的参数实例')
        return instance


class Product(models.Model):
    UNSHELVE = 0
    SHELVE = 1

    STATUS_CHOICES = (
        (UNSHELVE, '下架'),
        (SHELVE, '上架')
    )
    STATUS_JSON = [{'code': item[0], 'codeName': item[1]} for item in STATUS_CHOICES]
    name = models.CharField(verbose_name='名称', max_length=200)
    category = models.ForeignKey(Option, verbose_name='产品类型', on_delete=models.PROTECT, help_text='notes记录产品图标的名称')
    new_price = models.FloatField(verbose_name='新价格')
    old_price = models.FloatField(verbose_name='原价')
    thumbnail = models.ForeignKey(Upload, verbose_name='封面图', on_delete=models.PROTECT, null=True,
                                  related_name='thumbnail', blank=True)
    tags = models.CharField(verbose_name='标签', max_length=20, help_text='多个标签请用逗号隔开')
    images = models.ManyToManyField(Upload, verbose_name='图片s', related_name='product_images', blank=True)
    status = models.PositiveSmallIntegerField(choices=STATUS_CHOICES, verbose_name='状态')
    delete = models.BooleanField(verbose_name='删除', default=False)
    is_hot = models.BooleanField(verbose_name='热门', default=False)
    is_recommend = models.BooleanField(verbose_name='推荐', default=False)
    create_time = models.DateTimeField(verbose_name='创建时间', auto_now_add=True)
    details = models.TextField(verbose_name='详情', null=True, blank=True)
    details_images = models.ManyToManyField(Upload, verbose_name='详情图片s', related_name='product_details_images',
                                            blank=True)
    parameters = models.ManyToManyField(ProductParameter, verbose_name='参数', blank=True)

    class Meta:
        db_table = 'product'
        verbose_name = '产品'
        ordering = ['-id']

    @staticmethod
    def get_instance_by_id(id):
        try:
            id = int(id)
        except:
            raise CustomError('无效的产品id')

        instance = Product.objects.filter(pk=id).first()
        if not instance:
            raise CustomError('未找到对应的产品实例')
        return instance
